package com.hb.trade.api.push.task.wincandidatebulletinphase;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hb.core.pojo.Attachments;
import com.hb.core.pojo.project.deal.dto.BidCandidateDTO;
import com.hb.core.pojo.project.deal.dto.BidCandidateSectionDTO;
import com.hb.core.pojo.project.deal.entity.BidCandidateSection;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.trade.api.push.config.PushDataConfig;
import com.hb.trade.api.push.task.tenderbulletinphase.AttachmentSet;
import com.hb.trade.api.push.task.tenderprojectphase.BidSectionPushS;
import com.hb.trade.api.push.util.ConstantUtil;
import com.hb.trade.api.push.util.PushUtil;
import com.hb.trade.api.push.util.SFTPUtils;
import com.hb.trade.client.project.ProjectClient;
import com.jcraft.jsch.SftpException;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.fzzn.core.model.msg.Message;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * describe:
 *  中标候选人公示相关
 * @author zhongdl
 * @date 2022/02/23
 */
@Data
public class WinCandidateBulletinPhase {

    /**
     *项目编号
     */
    @JsonProperty("TENDER_PROJECT_CODE")
    private String tenderProjectCode;

    /**
     * 标段（包）编号
     */
    @JsonProperty("BID_SECTION_CODES")
    private BidSectionPushS bidSectionCodes;

    /**
     * 招标编号
     */
    @JsonProperty("TENDER_CODE")
    private String tenderCode;
    /**
     * 公示标题
     */
    @JsonProperty("PUBLICITY_NAME")
    private String publicityName;
    /**
     * 公示内容
     */
    @JsonProperty("PUBLICITY_CONTENT")
    private String publicityContent;
    /**
     * 公示类型
     */
    @JsonProperty("PUBLICITY_TYPE")
    private String publicityType;

    /**
     * 公示开始时间
     */
    @JsonProperty("PUBLICITY_START_TIME")
    private String publicityStartTime;
    /**
     * 公示结束时间
     */
    @JsonProperty("PUBLICITY_END_TIME")
    private String publicityEndTime;

    /**
     * 公告发布时间
     */
    @JsonProperty("NOTICE_SEND_TIME")
    private String noticeSendTime;
    /**
     * 公告发布媒介
     */
    @JsonProperty("NOTICE_MEDIA")
    private String noticeMedia;

    /**
     * 源URL
     */
    @JsonProperty("URL")
    private String url;
    /**
     * 提出异议的渠道和方式
     */
    @JsonProperty("OBJECTION_METHOD")
    private String objectionMethod;
    /**
     * 提出异议的渠道和方式
     */
    @JsonProperty("OTHER_CONTENT")
    private String otherContent;
    /**
     * 公告发布责任人
     */
    @JsonProperty("BULLETIN_DUTY")
    private String bulletinDuty;

    /**
     * 交易平台数据验证责任人姓名
     */
    @JsonProperty("EXAMINER_NAME")
    private String examinerName;

    @JsonProperty("SECTIONS_WIN_CANDIDATES")
    private SectionsWinCandidateS  sectionsWinCandidateS;
    /**
     * 附件列表
     */
    @JsonProperty("ATTACHMENT_SET")
    private List<Map<String, AttachmentSet>> attachmentSets;
    /**
     *交易平台或发布工具标识码
     */
    @JsonProperty("TRADE_PLAT")
    private String tradePlat;

    /**
     *公共服务平台标识码
     */
    @JsonProperty("PUB_SERVICE_PLAT_CODE")
    private String pubServicePlatCode;

    /**
     *数据时间戳
     */
    @JsonProperty("SUBMIT_TIMESTAMP")
    private String submitTimestamp;


    public WinCandidateBulletinPhase(BidCandidateDTO bidCandidateDTO) throws SftpException, IOException {
        //上传附件
        Attachments signFile = bidCandidateDTO.getPublicityContentSignature();
        if (CollUtil.isEmpty(signFile)){
            return;
        }
        String fileUrl = signFile.get(0).getFileUrl();
        boolean save = SFTPUtils.uploadFile(fileUrl);
        if (!save){
            return;
        }
        AttachmentSet attachmentSet = new AttachmentSet();
        attachmentSet.setAttachmentCode(PushUtil.getUuid());
        attachmentSet.setAttachmentFileName(FileUtil.getName(fileUrl).replaceAll("-",""));
        attachmentSet.setFileType("WIN_CANDIDATE_NOTICE_FILE");
        attachmentSet.setDataTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        attachmentSet.setMd5(SFTPUtils.getMD5(fileUrl));

        ProjectClient projectClient = SpringUtil.getBean(ProjectClient.class);

        AbstractProject project = new AbstractProject();
        project.setId(bidCandidateDTO.getProjectId());
        project.setWithSections(Boolean.TRUE);
        Message<AbstractProject> abstractProjectMessage = projectClient.projectDetail(project);
        if (abstractProjectMessage.isFail() || abstractProjectMessage.getData() == null){
            return;
        }
        project = abstractProjectMessage.getData();
        String bidSectionCode = "";
        List<BidCandidateSectionDTO> candidateSectionList = bidCandidateDTO.getCandidateSectionList();
        BidSectionPushS bidSectionCodes = new BidSectionPushS();
        List<String> bidSectionCodeList = CollUtil.list(false);
        //TODO 后边改成支架在表单取标段编号
        if (CollUtil.isNotEmpty(project.getSections()) && CollUtil.isNotEmpty(candidateSectionList)){
            List<Long> sectionIdList = candidateSectionList.stream().map(BidCandidateSection::getSectionId).collect(Collectors.toList());
            List<BidSectionDTO> sections = project.getSections();
            int size = project.getSections().size();
            for (int i = 0; i < size; i++) {
                BidSectionDTO bidSectionDTO = sections.get(i);
                if (sectionIdList.contains(bidSectionDTO.getId())){
                    bidSectionCodeList.add(bidSectionDTO.getSectionCode());
                    bidSectionCode = bidSectionDTO.getSectionCode();
                }

            }

        }
        bidSectionCodes.setBidSectionCodeList(bidSectionCodeList);
        //招标项目编号
        setTenderProjectCode(project.getTenderProjectCode());
        //标段（包）编号
        Map<String,String> bidSectionMap = MapUtil.newHashMap(1);
        bidSectionMap.put("BID_SECTION_CODE",bidSectionCode);
        setBidSectionCodes(bidSectionCodes);
        //
        setTenderCode("无");
        //公示标题
        setPublicityName(bidCandidateDTO.getPublicityName());
        //公示内容
        setPublicityContent(bidCandidateDTO.getNoticeContent().replaceAll("\\&[a-zA-Z]{1,10};", "").
                replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", ""));
        if (StrUtil.isBlank(getPublicityContent())){
            setPublicityContent("无");
        }
       //公示类型
        setPublicityType(bidCandidateDTO.getPublicityType() + "");
        //公示开始时间
        setPublicityStartTime(bidCandidateDTO.getPublicityStartTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //公示结束时间
        setPublicityEndTime(bidCandidateDTO.getPublicityEndTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //公告发布时间
        setNoticeSendTime(bidCandidateDTO.getDeployTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //公告发布媒介
        setNoticeMedia(StringUtils.isEmpty(bidCandidateDTO.getPublishMedium()) ? "/" : bidCandidateDTO.getPublishMedium());
        //源URL
        setUrl(PushDataConfig.portalUrl + "noticeDetail?id=" + bidCandidateDTO.getId() + "&bidTypeActive=3&queryType=2" );
        //提出异议的渠道和方式
        setObjectionMethod("线上");
        setOtherContent("/");
        //公告发布责任人
        setBulletinDuty(StrUtil.isEmpty(bidCandidateDTO.getCreateName()) ? "代理机构" : bidCandidateDTO.getCreateName());
        //交易平台数据验证责任人姓名
        setExaminerName(StrUtil.isEmpty(bidCandidateDTO.getCreateName()) ? "项目经理" : bidCandidateDTO.getCreateName());
        SectionsWinCandidateS sectionsWinCandidateS = new SectionsWinCandidateS();
        List<SectionsWinCandidate>  sectionsWinCandidateList = CollUtil.list(false);
        for (BidCandidateSectionDTO bidCandidateSectionDTO : candidateSectionList) {
            SectionsWinCandidate sectionsWinCandidate = new SectionsWinCandidate(bidCandidateSectionDTO.getSectionCode(), bidCandidateSectionDTO.getCandidateSupplierDTOList());
            sectionsWinCandidateList.add(sectionsWinCandidate);
        }
        sectionsWinCandidateS.setSectionsWinCandidateList(sectionsWinCandidateList);
        setSectionsWinCandidateS(sectionsWinCandidateS);

        //附件列表
        List<Map<String,AttachmentSet>> attachmentSets = CollUtil.list(false);
        Map<String, AttachmentSet> attachmentMap = MapUtil.newHashMap(1);
        attachmentMap.put("ATTACHMENT",attachmentSet);
        attachmentSets.add(attachmentMap);
        setAttachmentSets(attachmentSets);

        //交易平台或发布工具标识码
        setTradePlat(ConstantUtil.SOURCE_SYSTEM_ID);
        //公共服务平台标识码
        setPubServicePlatCode(ConstantUtil.TARGET_SYSTEM_ID_TEST);
        //时间戳
        setSubmitTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));

    }


}
